package com.smartshopping.iu;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.smartshopping.model.*;
import com.smartshopping.engine.*;

import android.os.Bundle;
import android.os.Parcelable;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;

public class ListGoodActivity extends Activity {

	private ArrayList<String> arrayStringItem;
	private ArrayList<Item> arrayItem;
	private ArrayList<TypeGood> arrayType;
	private ArrayList<String> arrayStringType;
	private ListAdapter arrayAdapter;
	private DataBaseHelper myDbHelper;
	private int curTypeGoodID = 0;
	private SearchEngine search = new SearchEngine();

	private EditText seachEditText;
	private int coopID = 0;
	private int marketID = 0;
	private ArrayList<Item> list = new ArrayList<Item>();
	private int curItem = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list_good);
		myDbHelper = new DataBaseHelper(this);
		try {
			myDbHelper.createDataBase(this);
			myDbHelper.openDataBase();
		} catch (IOException ioe) {
			throw new Error("Unable to create database");
		}

		// Get the basic value
		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		this.coopID = Integer.parseInt(extras.getString("coopID"));
		this.marketID = Integer.parseInt(extras.getString("marketID"));

		createListType();
		createListItem("", "", curTypeGoodID);

		// Create the handler of change in search edittext
		seachEditText = (EditText) findViewById(R.id.good_editText);
		seachEditText.addTextChangedListener(new TextWatcher() {
			public void afterTextChanged(Editable s) {
				createListItem(seachEditText.getText().toString(), "",
						curTypeGoodID);
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}
		});

		// Create the search button
		ImageButton searchButton = (ImageButton) findViewById(R.id.good_imageButton_search);
		searchButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				createListItem("", seachEditText.getText().toString(),
						curTypeGoodID);
			}
		});

		// Create type button
		ImageButton typeButton = (ImageButton) findViewById(R.id.good_imageButton_type);
		typeButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialogButtonClick();
			}
		});

		// Create bill button
		ImageButton billButton = (ImageButton) findViewById(R.id.good_imageButton_bill);
		billButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent myIntent1 = new Intent(ListGoodActivity.this,
						BillActivity.class);
				myIntent1.putExtra("coopID", Integer.toString(coopID));
				myIntent1.putExtra("marketID", Integer.toString(marketID));
				myIntent1.putParcelableArrayListExtra("list", list);
				ListGoodActivity.this.startActivityForResult(myIntent1, 2);
			}
		});
	}

	// Create the list of the good
	public void createListItem(String halfS, String fullS, int TypeGoodID) {
		// Get Intent
		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		// name.setText(extras.getString("name"));

		String cond = "";
		cond += "inner join stock on stock.ItemID = item._id "
				+ " where (stock.CoopID = " + extras.getString("coopID")
				+ " or stock.MarketID = " + extras.getString("marketID") + ") ";
		if (TypeGoodID > 0)
			cond += " And TypeID = " + Integer.toString(TypeGoodID);
		// Open database
		SQLiteDatabase mdb = myDbHelper.getReadableDatabase();
		String sql = "select * from item " + cond + " order by item.name ASC";
		System.out.println(sql);
		Cursor mCursor = mdb.rawQuery(sql, null);
		System.out.println(mCursor.getCount());
		// Create the array for the List
		arrayStringItem = new ArrayList<String>();
		arrayItem = new ArrayList<Item>();
		if (mCursor != null && mCursor.moveToFirst()) {
			do {
				// Add vao ArrayList
				if (search.checkIsOktoPutOnList(halfS, fullS,
						mCursor.getString(1))) {
					arrayStringItem.add(mCursor.getString(1));
					arrayItem.add(new Item(mCursor.getInt(0), mCursor
							.getString(1), mCursor.getInt(2)));
				}
			} while (mCursor.moveToNext());
		}
		mCursor.close();
		mdb.close();

		arrayAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, arrayStringItem);
		ListView listView = ((ListView) findViewById(R.id.good_listview));
		listView.setAdapter(arrayAdapter);

		// Set the list listener for the list
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> a, View v, int position,
					long id) {
				curItem = position;
				Intent myIntent1 = new Intent(ListGoodActivity.this,
						GoodDetailActivity.class);
				// Pass parameter to other activity
				myIntent1.putExtra("coopID",
						getIntent().getExtras().getString("coopID"));
				myIntent1.putExtra("name", arrayStringItem.get(position));
				myIntent1.putExtra("itemID",
						Integer.toString(arrayItem.get(position).getId()));
				int temp = isInBill(arrayItem.get(position).getId());
				if (temp != -1)
					myIntent1.putExtra("numberBuy",
							Integer.toString(list.get(temp).getAmount()));
				else
					myIntent1.putExtra("numberBuy", "0");
				ListGoodActivity.this.startActivityForResult(myIntent1, 1);
			}
		});
	}

	// Check the item after check is whether in bill or not
	private int isInBill(int id) {
		int temp = -1;
		for (int i = 0; i < this.list.size(); i++)
			if (this.list.get(i).getId() == id)
				temp = i;
		return temp;
	}

	// When the detail back, get the result and analsys it
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 1) {
			if (resultCode == RESULT_OK) {
				int numberBuy = Integer.parseInt(data
						.getStringExtra("numberBuy"));
				int price = Integer.parseInt(data.getStringExtra("price"));
				int temp = isInBill(arrayItem.get(curItem).getId());
				if (temp == -1 && numberBuy > 0)
					this.list.add(new Item(arrayItem.get(curItem).getId(),
							arrayItem.get(curItem).getName(), arrayItem.get(
									curItem).getTypeId(), numberBuy, price));
				else if (temp > -1 && numberBuy == 0)
					this.list.remove(temp);
				else if (temp > -1 && numberBuy > 0)
					this.list.get(temp).setAmount(numberBuy);
			}
			if (resultCode == RESULT_CANCELED) {
				// Write your code on no result return
			}
		} else if (requestCode == 2) {
			if (resultCode == RESULT_OK) {
				if (data.getStringExtra("saved") != null)
					this.finish();
				else {
					ArrayList<Parcelable> arrayList = data
							.getParcelableArrayListExtra("list");
					list.clear();
					for (int i = 0; i < arrayList.size(); i++)
						list.add((Item) arrayList.get(i));
				}
			}
			if (resultCode == RESULT_CANCELED) {
				// Write your code on no result return
			}
		}

	}

	// Create the list of type of good
	public void createListType() {
		// Open database
		SQLiteDatabase mdb = myDbHelper.getReadableDatabase();
		String sql = "select * from type";
		Cursor mCursor = mdb.rawQuery(sql, null);
		System.out.println(mCursor.getCount());

		// Create the array for the List
		arrayType = new ArrayList<TypeGood>();
		arrayStringType = new ArrayList<String>();
		arrayStringType.add("Tất cả");
		if (mCursor.moveToFirst()) {
			do {
				// Add vao ArrayList
				arrayStringType.add(mCursor.getString(1));
				arrayType.add(new TypeGood(mCursor.getInt(0), 0, mCursor
						.getString(1)));
			} while (mCursor.moveToNext());
		}
		mCursor.close();
		mdb.close();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.index, menu);
		return true;
	}

	// Create the dialog
	private void showDialogButtonClick() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Chọn loại sản phẩm");

		String[] choiceList = new String[arrayStringType.size()];
		choiceList = arrayStringType.toArray(choiceList);

		int selected = -1; // does not select anything
		builder.setSingleChoiceItems(choiceList, selected,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
						int position = ((AlertDialog) dialog).getListView()
								.getCheckedItemPosition();
						if (position > 0)
							curTypeGoodID = arrayType.get(position - 1).getId();
						else
							curTypeGoodID = 0;
						createListItem("", "", curTypeGoodID);
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}

}
